{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f725852e-71ef-4615-8cac-011a516fbe72",
   "metadata": {},
   "source": [
    "# Managing Agent Steps\n",
    "\n",
    "In this notebook we will go over how to build a basic agent executor where we custom handle how to manage the intermediate steps. Normally, all previous steps are passed to the agent at future iterations, but in long-running cases that could lead to an overly large amount of steps that you may want to trim\n",
    "\n",
    "This examples builds off the base agent executor. It is highly recommended you learn about that executor before going through this notebook. You can find documentation for that example [here](./base.ipynb).\n",
    "\n",
    "Any modifications of that example are called below with **MODIFICATION**, so if you are looking for the differences you can just search for that."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd763d4e-fd5e-4ce4-aa3a-54ab895d10a6",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First we need to install the packages required"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa752131-27e3-4bd8-9f21-d6749a7e74f4",
   "metadata": {},
   "outputs": [],
   "source": ["%%capture --no-stderr\n%pip install --quiet -U langgraph langchain langchain_openai tavily-python"]
  },
  {
   "cell_type": "markdown",
   "id": "dbbfe916-5c23-4bf4-a5fa-5048e676dae3",
   "metadata": {},
   "source": [
    "Next, we need to set API keys for OpenAI (the LLM we will use) and Tavily (the search tool we will use)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5732e68f-4ae2-4db9-bf9c-454b4cc9ec01",
   "metadata": {},
   "outputs": [],
   "source": ["import getpass\nimport os\n\nos.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\nos.environ[\"TAVILY_API_KEY\"] = getpass.getpass(\"Tavily API Key:\")"]
  },
  {
   "cell_type": "markdown",
   "id": "4141f30e-4e5a-4b98-9fd8-b95e859d203a",
   "metadata": {},
   "source": [
    "Optionally, we can set API key for [LangSmith tracing](https://smith.langchain.com/), which will give us best-in-class observability."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "652d4600-8f95-493f-b9b9-d4095aed9218",
   "metadata": {},
   "outputs": [],
   "source": ["os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\nos.environ[\"LANGCHAIN_API_KEY\"] = getpass.getpass(\"LangSmith API Key:\")"]
  },
  {
   "cell_type": "markdown",
   "id": "5dace4a9-7c9e-4da2-bf7b-e58d0d05581e",
   "metadata": {},
   "source": [
    "## Create the LangChain agent\n",
    "\n",
    "First, we will create the LangChain agent. For more information on LangChain agents, see [this documentation](https://python.langchain.com/v0.2/docs/concepts/#agents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4499eb16-bca8-4a60-9a3a-2f34ae3f7078",
   "metadata": {},
   "outputs": [],
   "source": ["from langchain import hub\nfrom langchain.agents import create_openai_functions_agent\nfrom langchain_community.tools.tavily_search import TavilySearchResults\nfrom langchain_openai.chat_models import ChatOpenAI\n\ntools = [TavilySearchResults(max_results=1)]\n\n# Get the prompt to use - you can modify this!\nprompt = hub.pull(\"hwchase17/openai-functions-agent\")\n\n# Choose the LLM that will drive the agent\nllm = ChatOpenAI(model=\"gpt-3.5-turbo-1106\", streaming=True)\n\n# Construct the OpenAI Functions agent\nagent_runnable = create_openai_functions_agent(llm, tools, prompt)"]
  },
  {
   "cell_type": "markdown",
   "id": "972e58b3-fe3c-449d-b3c4-8fa2217afd07",
   "metadata": {},
   "source": [
    "## Define the graph state\n",
    "\n",
    "We now define the graph state. The state for the traditional LangChain agent has a few attributes:\n",
    "\n",
    "1. `input`: This is the input string representing the main ask from the user, passed in as input.\n",
    "2. `chat_history`: This is any previous conversation messages, also passed in as input.\n",
    "3. `intermediate_steps`: This is list of actions and corresponding observations that the agent takes over time. This is updated each iteration of the agent.\n",
    "4. `agent_outcome`: This is the response from the agent, either an AgentAction or AgentFinish. The AgentExecutor should finish when this is an AgentFinish, otherwise it should call the requested tools.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c941fb10-dbe5-4d6a-ab7d-133d01c33cc4",
   "metadata": {},
   "outputs": [],
   "source": ["import operator\nfrom typing import Annotated, TypedDict, Union\n\nfrom langchain_core.agents import AgentAction, AgentFinish\nfrom langchain_core.messages import BaseMessage\n\n\nclass AgentState(TypedDict):\n    # The input string\n    input: str\n    # The list of previous messages in the conversation\n    chat_history: list[BaseMessage]\n    # The outcome of a given call to the agent\n    # Needs `None` as a valid type, since this is what this will start as\n    agent_outcome: Union[AgentAction, AgentFinish, None]\n    # List of actions and corresponding observations\n    # Here we annotate this with `operator.add` to indicate that operations to\n    # this state should be ADDED to the existing values (not overwrite it)\n    intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]"]
  },
  {
   "cell_type": "markdown",
   "id": "cd27b281-cc9a-49c9-be78-8b98a7d905c4",
   "metadata": {},
   "source": [
    "## Define the nodes\n",
    "\n",
    "We now need to define a few different nodes in our graph.\n",
    "In `langgraph`, a node can be either a function or a [runnable](https://python.langchain.com/v0.2/docs/concepts/#langchain-expression-language-lcel).\n",
    "There are two main nodes we need for this:\n",
    "\n",
    "1. The agent: responsible for deciding what (if any) actions to take.\n",
    "2. A function to invoke tools: if the agent decides to take an action, this node will then execute that action.\n",
    "\n",
    "We will also need to define some edges.\n",
    "Some of these edges may be conditional.\n",
    "The reason they are conditional is that based on the output of a node, one of several paths may be taken.\n",
    "The path that is taken is not known until that node is run (the LLM decides).\n",
    "\n",
    "1. Conditional Edge: after the agent is called, we should either:\n",
    "   a. If the agent said to take an action, then the function to invoke tools should be called\n",
    "   b. If the agent said that it was finished, then it should finish\n",
    "2. Normal Edge: after the tools are invoked, it should always go back to the agent to decide what to do next\n",
    "\n",
    "Let's define the nodes, as well as a function to decide how what conditional edge to take."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "77e3c059-e31f-4c8f-81bf-edb58688e12b",
   "metadata": {},
   "outputs": [],
   "source": ["from langchain_core.agents import AgentFinish\n\nfrom langgraph.prebuilt.tool_executor import ToolExecutor\n\n# This a helper class we have that is useful for running tools\n# It takes in an agent action and calls that tool and returns the result\ntool_executor = ToolExecutor(tools)"]
  },
  {
   "cell_type": "markdown",
   "id": "4c804a34-d384-4ca9-b9fc-dc86d678ab39",
   "metadata": {},
   "source": [
    "**MODIFICATION**\n",
    "\n",
    "Here, we modify the agent to only look at the last five intermediate steps. This is a relatively simple example of shortening the intermediate step history."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a9f66a3e-aba1-4893-95b1-a433c7091d5e",
   "metadata": {},
   "outputs": [],
   "source": ["# Define the agent\ndef run_agent(data):\n    inputs = data.copy()\n    if len(inputs[\"intermediate_steps\"]) > 5:\n        inputs[\"intermediate_steps\"] = inputs[\"intermediate_steps\"][-5:]\n    agent_outcome = agent_runnable.invoke(inputs)\n    return {\"agent_outcome\": agent_outcome}\n\n\n# Define the function to execute tools\ndef execute_tools(data):\n    # Get the most recent agent_outcome - this is the key added in the `agent` above\n    agent_action = data[\"agent_outcome\"]\n    output = tool_executor.invoke(agent_action)\n    return {\"intermediate_steps\": [(agent_action, str(output))]}\n\n\n# Define logic that will be used to determine which conditional edge to go down\ndef should_continue(data):\n    # If the agent outcome is an AgentFinish, then we return `exit` string\n    # This will be used when setting up the graph to define the flow\n    if isinstance(data[\"agent_outcome\"], AgentFinish):\n        return \"end\"\n    # Otherwise, an AgentAction is returned\n    # Here we return `continue` string\n    # This will be used when setting up the graph to define the flow\n    else:\n        return \"continue\""]
  },
  {
   "cell_type": "markdown",
   "id": "c0b211f4-0c5c-4792-b18d-cd70907c71e7",
   "metadata": {},
   "source": [
    "## Define the graph\n",
    "\n",
    "We can now put it all together and define the graph!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c4054dde-4618-49b7-998a-daa0c1d6d6c0",
   "metadata": {},
   "outputs": [],
   "source": ["from langgraph.graph import END, StateGraph, START\n\n# Define a new graph\nworkflow = StateGraph(AgentState)\n\n# Define the two nodes we will cycle between\nworkflow.add_node(\"agent\", run_agent)\nworkflow.add_node(\"action\", execute_tools)\n\n# Set the entrypoint as `agent`\n# This means that this node is the first one called\nworkflow.add_edge(START, \"agent\")\n\n# We now add a conditional edge\nworkflow.add_conditional_edges(\n    # First, we define the start node. We use `agent`.\n    # This means these are the edges taken after the `agent` node is called.\n    \"agent\",\n    # Next, we pass in the function that will determine which node is called next.\n    should_continue,\n    # Finally we pass in a mapping.\n    # The keys are strings, and the values are other nodes.\n    # END is a special node marking that the graph should finish.\n    # What will happen is we will call `should_continue`, and then the output of that\n    # will be matched against the keys in this mapping.\n    # Based on which one it matches, that node will then be called.\n    {\n        # If `tools`, then we call the tool node.\n        \"continue\": \"action\",\n        # Otherwise we finish.\n        \"end\": END,\n    },\n)\n\n# We now add a normal edge from `tools` to `agent`.\n# This means that after `tools` is called, `agent` node is called next.\nworkflow.add_edge(\"action\", \"agent\")\n\n# Finally, we compile it!\n# This compiles it into a LangChain Runnable,\n# meaning you can use it as you would any other runnable\napp = workflow.compile()"]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "214ae46e-c297-465d-86db-2b0312ed3530",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'agent_outcome': AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'weather in San Francisco'}, log=\"\\nInvoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\\n\\n\\n\", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\"query\":\"weather in San Francisco\"}', 'name': 'tavily_search_results_json'}})])}\n",
      "----\n",
      "{'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'weather in San Francisco'}, log=\"\\nInvoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\\n\\n\\n\", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\"query\":\"weather in San Francisco\"}', 'name': 'tavily_search_results_json'}})]), \"[{'url': 'https://en.climate-data.org/north-america/united-states-of-america/california/san-francisco-385/t/january-1/', 'content': 'San Francisco Weather in January  San Francisco weather in January San Francisco weather by month // weather averages 9.6 (49.2) 6.2 (43.2) 14 (57.3) 113  San Francisco weather in January // weather averages Airport close to San Francisco  you can find all information about the weather in San Francisco in January:Data: 1991 - 2021 Min. Temperature °C (°F), Max. Temperature °C (°F), Precipitation / Rainfall mm (in), Humidity, Rainy days. Data: 1999 - 2019: avg. Sun hours San Francisco weather and climate for further months San Francisco in February San Francisco in March San Francisco in April San Francisco in May San Francisco in June San Francisco in July'}]\")]}\n",
      "----\n",
      "{'agent_outcome': AgentFinish(return_values={'output': \"The weather in San Francisco varies by month. In January, the average minimum temperature is 9.6°C (49.2°F), and the average maximum temperature is 14°C (57.3°F). The city experiences an average of 113mm of precipitation and has an average of 6 rainy days in January. If you'd like to know more about the weather in other months, feel free to ask!\"}, log=\"The weather in San Francisco varies by month. In January, the average minimum temperature is 9.6°C (49.2°F), and the average maximum temperature is 14°C (57.3°F). The city experiences an average of 113mm of precipitation and has an average of 6 rainy days in January. If you'd like to know more about the weather in other months, feel free to ask!\")}\n",
      "----\n",
      "{'input': 'what is the weather in sf', 'chat_history': [], 'agent_outcome': AgentFinish(return_values={'output': \"The weather in San Francisco varies by month. In January, the average minimum temperature is 9.6°C (49.2°F), and the average maximum temperature is 14°C (57.3°F). The city experiences an average of 113mm of precipitation and has an average of 6 rainy days in January. If you'd like to know more about the weather in other months, feel free to ask!\"}, log=\"The weather in San Francisco varies by month. In January, the average minimum temperature is 9.6°C (49.2°F), and the average maximum temperature is 14°C (57.3°F). The city experiences an average of 113mm of precipitation and has an average of 6 rainy days in January. If you'd like to know more about the weather in other months, feel free to ask!\"), 'intermediate_steps': [(AgentActionMessageLog(tool='tavily_search_results_json', tool_input={'query': 'weather in San Francisco'}, log=\"\\nInvoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\\n\\n\\n\", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{\"query\":\"weather in San Francisco\"}', 'name': 'tavily_search_results_json'}})]), \"[{'url': 'https://en.climate-data.org/north-america/united-states-of-america/california/san-francisco-385/t/january-1/', 'content': 'San Francisco Weather in January  San Francisco weather in January San Francisco weather by month // weather averages 9.6 (49.2) 6.2 (43.2) 14 (57.3) 113  San Francisco weather in January // weather averages Airport close to San Francisco  you can find all information about the weather in San Francisco in January:Data: 1991 - 2021 Min. Temperature °C (°F), Max. Temperature °C (°F), Precipitation / Rainfall mm (in), Humidity, Rainy days. Data: 1999 - 2019: avg. Sun hours San Francisco weather and climate for further months San Francisco in February San Francisco in March San Francisco in April San Francisco in May San Francisco in June San Francisco in July'}]\")]}\n",
      "----\n"
     ]
    }
   ],
   "source": ["inputs = {\"input\": \"what is the weather in sf\", \"chat_history\": []}\nfor s in app.stream(inputs):\n    print(list(s.values())[0])\n    print(\"----\")"]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2eb662bc-de7d-4a57-a3e8-2f00dcf4ff8b",
   "metadata": {},
   "outputs": [],
   "source": [""]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
